import React, { useEffect, useState } from 'react';
import { MemberEntity } from '../model/member'
import { getMembersCollections } from '../api/memberApi'

const useLoadMemberCollection = () => {
  const [memberCollection, setmemberCollection] = useState<MemberEntity[]>([])
  const loadMemberCollection = async () => {
    const newMemberCollection = await getMembersCollections()
    setmemberCollection(newMemberCollection)
  }
  return { memberCollection, loadMemberCollection }
}

export const MemberTableComponent: React.FC = () => {
  const { memberCollection, loadMemberCollection } = useLoadMemberCollection()
  useEffect(() => {
    loadMemberCollection()
  }, [])
  return (
    <>
      <table>
        <thead>
          <tr>
            <th>Avatar</th>
            <th>Id</th>
            <th>Name</th>
          </tr>
        </thead>
        <tbody>
          {
            memberCollection.map((member) => {
              return <MemberRow member={member} key={member.name + member.avatar_url} />
            })
          }
        </tbody>
      </table>
    </>
  )
}

const MemberRow = ({ member }: { member: MemberEntity }) => {
  return (
    <>
      <tr>
        <td>
          <span>{member.name}</span>
        </td>
        <td>
          <span>{member.login}</span>
        </td>
        <td>
          <img src={member.avatar_url} style={{ maxWidth: '10rem' }} alt="" />
        </td>
      </tr>
    </>
  )
}